/*
GANESHA - Reasoning on critical infrastructures affected by emergency situations
Copyright (c) 2010-2011, Information Eng. Research Unit - Univ. of Alcala
http://www.cc.uah.es/ie
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along
with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

package es.uah.cc.ie.ganesha.messaging.position;

/**
 * Represents a polygonal position for an incident.
 * @author ieru
 */
public class PolygonPosition extends MessagePosition {

	double[] _longPoints, _latPoints;
	int _npoints;

	/**
	 * Constructor
	 * @param latPoints List (array) of latitudes of the points of the polygon
	 * @param longPoints List (array) of longitudes of the points of the polygon
	 * @param npoints Number of points of the polygon
	 */
	public PolygonPosition(double[] latPoints, double[] longPoints, int npoints)
	{
		_longPoints = longPoints;
		_latPoints = latPoints;
		_npoints = npoints;
	}

	/**
	 * Check if a given point is inside a given (complex) polygon.
	 *
	 * @param latitude Latitude
	 * @param longitude Longitude
	 * @return  True if the given point is inside the polygon, false otherwise.
	 */
	@Override
	public boolean isInArea(double latitude, double longitude) {
		boolean isInside = false;

		int j = 0;
		for (int i = 0; i < _npoints; i++) {
			j++;
			if (j == _npoints) {
				j = 0;
			}

			if (_longPoints[i] < longitude && _longPoints[j] >= longitude || _longPoints[j] < longitude && _longPoints[i] >= longitude) {
				if (_latPoints[i] + (longitude - _longPoints[i]) / (_longPoints[j] - _longPoints[i]) * (_latPoints[j] - _latPoints[i]) < latitude) {
					isInside = !isInside;
				}
			}
		}

		return isInside;
	}

	/**
	 * Returns the longitude of the center of the polygon
	 * @return The longitude of the center of the polygon
	 */
	@Override
	public double getCenterLongitude() {
		double result = 0;

		for(int i = 0; i < _npoints ; i++)
			result += _longPoints[i];

		return result / (double)_npoints;
	}

	/**
	 * Returns the latitude of the center of the polygon
	 * @return The latitude of the center of the polygon
	 */
	@Override
	public double getCenterLatitude() {
		double result = 0;

		for(int i = 0; i < _npoints ; i++)
			result += _latPoints[i];

		return result / (double)_npoints;
	}
}
